
import numpy as np
import shapely
from shapely.geometry import Polygon
import matplotlib.pyplot as plt

coordinates = [[68.91, 249.74], [51.45, 214.12], [87.86, 215.84], [29.25, 190.46], [23, 156.18], [35.16, 52.97], [70.95, 60.51], [54.36, 26.57]]
coordinate_x = [68.91, 51.45, 87.86, 29.25, 23, 35.16, 70.95, 54.36]
coordinate_y = [249.74, 214.12, 215.84, 190.46, 156.18, 52.97, 60.51, 26.57]
coordinates_beta = [[29.25, 190.46], [51.45, 214.12], [68.91, 249.74], [87.86, 215.84], [70.95, 60.51], [54.36, 26.57], [35.16, 52.97], [23, 156.18]]
coordinate_beta_x = [29.25, 51.45, 68.91, 87.86, 70.95, 54.36, 35.16, 23]
coordinate_beta_y = [190.46, 214.12, 249.74, 215.84, 60.51, 26.57, 52.97, 156.18]
 
 
def calulate_iou(shape1, shape2):
    # 代码来源：https://blog.csdn.net/u012433049/article/details/82909484
    # 只能计算凸边形的iou
    poly1 = Polygon(shape1).convex_hull  # python四边形对象，会自动计算四个点，最后四个点顺序为：左上 左下  右下 右上 左上
    poly2 = Polygon(shape2).convex_hull
 
    union_poly = np.concatenate((shape1, shape2))  # 合并两个box坐标，变为8*2
    if not poly1.intersects(poly2):  # 如果两四边形不相交
        iou = 0
    else:
        try:
            inter_area = poly1.intersection(poly2).area  # 相交面积
            print("inter_area:", inter_area)
 
            # union_area = MultiPoint(union_poly).convex_hull.area  # 包含两个四边形最小多边形的面积，第一种算法
            union_area = poly1.area + poly2.area - inter_area  # 两四边形并集，第二种常见算法
 
            print("union_area:", union_area)
            if union_area == 0:
                iou = 0
            iou = float(inter_area) / union_area
            """
            源码中给出了两种IOU计算方式:
            第一种：交集部分/包含两个四边形最小多边形的面积
            第二种：交集 / 并集（常见矩形框IOU计算方式）
            """
        except shapely.geos.TopologicalError:
            print('shapely.geos.TopologicalError occured, iou set to 0')
            iou = 0
    return [iou, inter_area, union_area]


def calculate_center(pressure_arrays, saved_picture_path=None, is_left=True): # 计算重心坐标
    '''
    pressure_arrays = [[p11, p12, p13, p14, p15, p16, p17, p18],
                       [p21, p22, p23, p24, p25, p26, p27, p28],
                       ......]
    '''
    center_array = []
    for pressure in pressure_arrays:
        Gx = np.multiply(np.array(pressure),np.array(coordinate_beta_x)).sum() / np.array(pressure).sum()
        Gy = np.multiply(np.array(pressure),np.array(coordinate_beta_y)).sum() / np.array(pressure).sum()
        center_array.append([Gx, Gy])

    if saved_picture_path is not None:
        png_path = "G:\\PytonGrpcDemo\\left.png" if is_left else "G:\\PytonGrpcDemo\\right.png"
        print(png_path)
        img=plt.imread(png_path)
        plt.imshow(img, extent=[0,110,0,280])
        plt.scatter(np.array(center_array)[:, 0],np.array(center_array)[:, 1], marker='o', c='y')
        plt.savefig(saved_picture_path)

    return center_array


if __name__ == "__main__":
    pressure_arrays = np.random.uniform(low=0.0, high=20.0,size=(10, 8))
    calculate_center(pressure_arrays, "./right_center.png", False)